<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 引入 Bootstrap v3 的 CSS 文件 -->
    <link rel="stylesheet" href="bootstrap-3.4.1/css/bootstrap.css">
    <!-- 引入 jQuery（Bootstrap v3 依赖） -->
    <script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.1.1/jquery.min.js"></script>
    <!-- 引入 Bootstrap v3 的 JS 文件 -->
    <script src="bootstrap-3.4.1/js/bootstrap.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.9.0/axios.js"></script>
    <title>字典管理界面</title>
    <style>
        :root {
            --primary-color: #4a6cf7;
            --secondary-color: #6c757d;
            --success-color: #28a745;
            --danger-color: #dc3545;
            --warning-color: #ffc107;
            --info-color: #17a2b8;
            --bg-color: #f8f9fa;
            --card-bg: #ffffff;
            --border-color: #e9ecef;
            --box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.1);
            --transition: all 0.3s ease;
        }

        body {
            background-color: var(--bg-color);
            color: #333;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .navbar {
            background-color: var(--card-bg);
            border-bottom: 1px solid var(--border-color);
            box-shadow: var(--box-shadow);
            margin-bottom: 20px;
        }

        .navbar-brand {
            font-weight: 600;
            color: var(--primary-color) !important;
            font-size: 1.5rem;
        }

        .form-control {
            border-radius: 8px;
            padding: 12px 15px;
            height: auto;
            border: 1px solid var(--border-color);
            transition: var(--transition);
            box-shadow: none;
        }

        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(74, 108, 247, 0.2);
            outline: none;
        }

        .btn {
            border-radius: 8px;
            padding: 8px 16px;
            font-weight: 500;
            transition: var(--transition);
        }

        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }

        .btn-primary:hover {
            background-color: #3a5ce0;
            border-color: #3a5ce0;
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(74, 108, 247, 0.3);
        }

        .btn-danger {
            background-color: var(--danger-color);
            border-color: var(--danger-color);
        }

        .btn-danger:hover {
            background-color: #c82333;
            border-color: #c82333;
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(220, 53, 69, 0.3);
        }

        .btn-info {
            background-color: var(--info-color);
            border-color: var(--info-color);
        }

        .btn-info:hover {
            background-color: #138496;
            border-color: #138496;
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(23, 162, 184, 0.3);
        }

        .table {
            margin-bottom: 20px;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: var(--box-shadow);
        }

        .table thead {
            background-color: #f1f3f5;
        }

        .table th,
        .table td {
            padding: 12px 15px;
            vertical-align: middle;
            border-color: var(--border-color);
        }

        .table-striped tbody tr:nth-of-type(odd) {
            background-color: rgba(0, 0, 0, 0.02);
        }

        .pagination {
            margin-top: 20px;
        }

        .pagination>li>a,
        .pagination>li>span {
            border-radius: 50%;
            min-width: 36px;
            height: 36px;
            line-height: 24px;
            padding: 0;
            text-align: center;
            margin: 0 4px;
        }

        .pagination>li.active>a,
        .pagination>li.active>span {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }

        .pagination>li>a:hover,
        .pagination>li>span:hover {
            background-color: #f0f2f5;
        }

        .modal-content {
            border-radius: 12px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        }

        .modal-header {
            border-bottom: 1px solid var(--border-color);
            padding: 20px 30px;
        }

        .modal-title {
            font-weight: 600;
            color: #212529;
        }

        .modal-body {
            padding: 20px 30px;
        }

        .modal-footer {
            border-top: 1px solid var(--border-color);
            padding: 15px 30px;
        }

        .close {
            font-size: 1.5rem;
            color: #6c757d;
        }

        .close:hover {
            color: #212529;
        }

        #cancel {
            font-size: 16px;
            padding: 5px 10px;
            color: var(--secondary-color);
            cursor: pointer;
        }

        .note-label {
            vertical-align: top;
            padding-top: 6px;
        }

        #note {
            resize: none;
            min-height: 100px;
        }

        /* 自定义状态标签 */
        .status-tag {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
            margin-right: 5px;
        }

        .status-enable {
            background-color: rgba(40, 167, 69, 0.1);
            color: var(--success-color);
            border: 1px solid rgba(40, 167, 69, 0.2);
        }

        .status-disable {
            background-color: rgba(220, 53, 69, 0.1);
            color: var(--danger-color);
            border: 1px solid rgba(220, 53, 69, 0.2);
        }

        /* 按钮悬停效果 */
        .btn-xs {
            padding: 4px 8px;
            font-size: 12px;
        }

        /* 卡片样式 */
        .card {
            background-color: var(--card-bg);
            border-radius: 8px;
            border: 1px solid var(--border-color);
            box-shadow: var(--box-shadow);
            margin-bottom: 20px;
        }

        .card-header {
            padding: 15px 20px;
            border-bottom: 1px solid var(--border-color);
            font-weight: 600;
            color: #212529;
        }

        .card-body {
            padding: 20px;
        }
    </style>

</head>

<body>

<nav class="navbar navbar-default">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">字典管理</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <form class="navbar-form navbar-left">
                <div class="form-group">
                    <input type="text" class="form-control" placeholder="字典类型">
                </div>
                <div class="form-group">
                    <input type="text" class="form-control" placeholder="字典名称">
                </div>
                <div class="form-group">
                    <select class="form-control">
                        <option value="-1">所有</option>
                        <option value="0">启用</option>
                        <option value="1">禁用</option>
                    </select>
                </div>
                <button class="btn btn-primary">查询</button>
            </form>
            <ul class="nav navbar-nav navbar-right">
                <li><a href="#" data-toggle="modal" data-target="#addDictModal">添加字典</a></li>
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
                       aria-expanded="false">操作 <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="#">刷新数据</a></li>
                        <li><a href="#">导出数据</a></li>
                        <li><a href="#">导入数据</a></li>
                        <li role="separator" class="divider"></li>
                        <li><a href="#">系统设置</a></li>
                    </ul>
                </li>
            </ul>
        </div><!-- /.navbar-collapse -->
    </div><!-- /.container-fluid -->
</nav>

<!-- 数据字典的表格 -->
<div class="card">
    <div class="card-header">数据字典列表</div>
    <div class="card-body">
        <table class="table table-bordered table-striped table-condensed">
            <thead>
            <th>#</th>
            <th>字典名称</th>
            <th>字典类型</th>
            <th>状态</th>
            <th>备注</th>
            <th>创建时间</th>
            <th>操作</th>
            </thead>
            <tbody id="dict-tbody">
            <!-- 动态插入数据 -->
            </tbody>

            <tfoot>
            <tr>
                <td colspan="7" style="text-align: center;">
                    <nav aria-label="Page navigation">
                        <ul class="pagination" id="pagination">
                            <!-- 动态插入分页 -->
                        </ul>
                    </nav>
                </td>
            </tr>
            </tfoot>
        </table>
    </div>
</div>

<!-- 编辑模态框 -->
<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="editModalLabel">编辑字典</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label for="inputDname" class="col-sm-2 control-label">字典名称</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="inputDname" placeholder="请输入字典名称">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="editDtype" class="col-sm-2 control-label">字典类型</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="editDtype" placeholder="请输入字典类型">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="editStatus" class="col-sm-2 control-label">字典状态</label>
                        <div class="col-sm-10">
                            <div class="checkbox">
                                <label>
                                    <input type="radio" value="0" name="editState">
                                    <span class="status-tag status-enable">启用</span>
                                </label>
                                <label>
                                    <input type="radio" value="1" name="editState">
                                    <span class="status-tag status-disable">禁用</span>
                                </label>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="handleSave()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 删除模态框 -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="deleteModalLabel">删除确认</h4>
            </div>
            <div class="modal-body">
                <div id="cancel" class="fs-6 "></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="handleDelConfirm()">确认删除</button>
            </div>
        </div>
    </div>
</div>

<!-- 添加字典模态框 -->
<div class="modal fade" id="addDictModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">添加字典</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label for="addInputDname" class="col-sm-2 control-label">字典名称</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="addInputDname" placeholder="请输入字典名称">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="addInputDtype" class="col-sm-2 control-label">字典类型</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="addInputDtype" placeholder="请输入字典类型">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="inputStatus" class="col-sm-2 control-label">字典状态</label>
                        <div class="col-sm-10">
                            <div class="checkbox">
                                <label>
                                    <input type="radio" value="0" name="dstate">
                                    <span class="status-tag status-enable">启用</span>
                                </label>
                                <label>
                                    <input type="radio" value="1" name="dstate">
                                    <span class="status-tag status-disable">禁用</span>
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="inputStatus" class="col-sm-2 control-label note-label">备注</label>
                        <div class="col-sm-10">
								<textarea id="note" class="form-control" maxlength="200"
                                          placeholder="请在此输入备注信息..."></textarea>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="onSave()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 字典详情列表模态框 -->
<div class="modal fade" id="dictDetailModal" tabindex="-1" role="dialog" aria-labelledby="detailModalLabel">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="detailModalLabel">字典详情列表</h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-12">
                        <div class="panel panel-default card">
                            <div class="panel-heading card-header">
                                <h5 id="detailTitle">字典详情</h5>
                            </div>
                            <div class="panel-body card-body">
                                <table class="table table-bordered table-striped table-condensed">
                                    <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>字典标签</th>
                                        <th>字典键值</th>
                                        <th>排序</th>
                                        <th>状态</th>
                                        <th>备注</th>
                                        <th>创建时间</th>
                                        <th>操作</th>
                                    </tr>
                                    </thead>
                                    <tbody id="dict-detail-tbody">
                                    <!-- 动态插入字典详情数据 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="addDictDetail()">添加详情</button>
            </div>
        </div>
    </div>
</div>

<script>
    let currentPage = 1;
    let pageSize = 10;
    let editData = null;
    let deleteId = 0;

    function fetchDictData(pageNum = 1, pageSize = 10) {
        axios.get(`http://localhost/dict/find/${pageNum}/${pageSize}`)
            .then(res => {
                // 假设返回数据格式为 { data: { list: [...], total: 100, pageNum: 1, pageSize: 10 } }
                const data = res.data.data;
                console.log(data);
                const total = data.total;
                console.log(total);
                renderTable(data.list);
                renderPagination(data.pageNum, data.pageSize, data.total);
            })
            .catch(err => {
                alert('数据加载失败');
            });
    }

    function renderTable(list) {
        const tbody = document.getElementById('dict-tbody');
        tbody.innerHTML = '';
        list.forEach((item, idx) => {
            tbody.innerHTML += `
			  <tr>
				<td>${item.id}</td>
				<td>${item.dname}</td>
				<td>${item.dtype}</td>
				<td>${item.dstate == 0 ? '<span class="status-tag status-enable">启用</span>' : '<span class="status-tag status-disable">禁用</span>'}</td>
				<td>${item.mark || ''}</td>
				<td>${item.createTime || ''}</td>
				<td>
				  <button class="btn btn-primary btn-xs"  data-toggle="modal" data-target="#editModal" onclick="handleEdit(${item.id})">编辑</button>
				<button class="btn btn-info btn-xs" data-toggle="modal" data-target="#dictDetailModal" onclick="fetchDictDetails(${item.id})" >列表</button>
				  <button class="btn btn-danger btn-xs" data-toggle="modal" data-target="#deleteModal" onclick="handleDelete(${item.id})">删除</button>
				</td>
			  </tr>
			`;
        });
    }

    async function handleEdit(id) {
        const res = await axios.get(`http://localhost/dict/find/${id}`);
        if (res.data.code != 200) return alert(res.data.message);

        editData = res.data.data;
        const forms = {
            editInput: document.getElementById('inputDname'),
            editDtype: document.getElementById('editDtype'),
            editStatus: document.querySelectorAll('input[name="editState"]'),
        }
        forms.editInput.value = res.data.data.dname;
        forms.editDtype.value = res.data.data.dtype;
        forms.editStatus.forEach(el => {
            if (el.value == res.data.data.dstate) {
                el.checked = true;
            }
        });

    }

    async function handleSave() {
        const forms = {
            editInput: document.getElementById('inputDname'),
            editDtype: document.getElementById('editDtype'),
            editStatus: document.querySelector('input[name="editState"]:checked'),
        }
        const data = {
            dname: forms.editInput.value,
            dtype: forms.editDtype.value,
            dstate: parseInt(forms.editStatus.value),
        }


        if (!data.dname) {
            return alert('请输入字典名称');
        }
        if (!data.dtype) {
            return alert('请输入字典类型');
        }
        if (data.dstate == undefined) {
            return alert('请选择字典状态');
        }
        const newdata = { ...editData, ...data };

        const res = await axios.post(`http://localhost/dict/update`, newdata);
        if (res.data.code == 200) {
            alert('保存成功');
            $('#editModal').modal('hide');
            fetchDictData();
        }

    }

    async function handleDelete(id) {
        const res = await axios.get(`http://localhost/dict/find/${id}`);
        deleteId = id;
        const html = document.querySelector("#cancel")
        if (res.data.code == 200) {
            html.innerText = `确定要删除数据字典:${res.data.data.dname}吗？此操作不可恢复。`
        }

    }
    async function handleDelConfirm() {
        const res = await axios.delete(`http://localhost/dict/delete/${deleteId}`);
        if (res.data.code == 200) {
            fetchDictData();
            $('#deleteModal').modal('hide');
        }
    }

    function renderPagination(pageNum, pageSize, total) {
        const page = Math.ceil(total / pageSize);
        const pageCount = page >= 5 ? 5 : page;
        const pagination = document.getElementById('pagination');
        let html = '';
        console.log("curr", currentPage);
        html += `<li>
			<a href="#" aria-label="Previous" >
			  <span >总页数: ${page}</span>
			</a>
		  </li>`;
        html += `<li${pageNum === 1 ? ' class="disabled"' : ''}>
						<a href="#" aria-label="Previous" onclick="gotoPage(${pageNum - 1})">
						  <span aria-hidden="true">&laquo;</span>
						</a>
			</li>`;

        if (pageNum > 5) {
            for (let i = pageNum - 4; i <= pageNum; i++) {
                html += `<li${i === pageNum ? ' class="active"' : ''}>
						  <a href="#" onclick="gotoPage(${i})">${i}</a>
						</li>`;
            }
        }
        else {
            for (let i = 1; i <= pageCount; i++) {
                html += `<li${i === pageNum ? ' class="active"' : ''}>
			  			  <a href="#" onclick="gotoPage(${i})">${i}</a>
			  			</li>`;
            }
        }

        html += `<li${pageNum === pageCount ? ' class="disabled"' : ''}>
			<a href="#" aria-label="Next" onclick="gotoPage(${pageNum + 1})">
			  <span aria-hidden="true">&raquo;</span>
			</a>
		  </li>`;
        pagination.innerHTML = html;
    }

    function gotoPage(page) {
        if (page < 1) return;
        currentPage = page;
        fetchDictData(currentPage, pageSize);
    }

    // 页面加载时获取第一页
    fetchDictData(currentPage, pageSize);

    // 查询字典详情数据
    function fetchDictDetails(dictName) {
        const requestData = {
            dname: dictName
        };

        axios.post('http://localhost/dict/findAll', requestData)
            .then(res => {
                if (res.data.code === 200) {
                    renderDictDetailTable(res.data.data);
                } else {
                    alert('查询字典详情失败：' + res.data.message);
                }
            })
            .catch(err => {
                console.error('查询字典详情失败:', err);
                alert('查询字典详情失败，请检查网络连接');
            });
    }



    // 渲染字典详情表格
    function renderDictDetailTable(detailList) {
        const tbody = document.getElementById('dict-detail-tbody');
        tbody.innerHTML = '';

        if (!detailList || detailList.length === 0) {
            tbody.innerHTML = '<tr><td colspan="8" class="text-center">暂无数据</td></tr>';
            return;
        }

        detailList.forEach((item, idx) => {
            // 处理时间格式
            const formatTime = (timeStr) => {
                if (!timeStr) return '';
                return new Date(timeStr).toLocaleString();
            };

            tbody.innerHTML += `
					<tr>
						<td>${item.id}</td>
						<td>${item.dtag || ''}</td>
						<td>${item.dval || ''}</td>
						<td>${item.dorder || ''}</td>
						<td>${item.state == 0 ? '<span class="status-tag status-enable">启用</span>' : '<span class="status-tag status-disable">禁用</span>'}</td>
						<td>${item.mark || ''}</td>
						<td>${formatTime(item.createTime) || ''}</td>
						<td>
							<button class="btn btn-primary btn-xs" onclick="editDictDetail(${item.id})">编辑</button>
							<button class="btn btn-danger btn-xs" onclick="deleteDictDetail(${item.id})">删除</button>
						</td>
					</tr>
				`;
        });
    }

</script>

<script>
    // 添加数据字典
    async function onSave() {
        const forms = {
            dname: document.getElementById('addInputDname'),
            dtype: document.getElementById('addInputDtype'),
            dstate: document.querySelector('input[name="dstate"]:checked'),
            mark: document.getElementById('note'),
        }
        const data = {
            dname: forms.dname.value,
            dtype: forms.dtype.value,
            dstate: parseInt(forms.dstate.value),
            mark: forms.mark.value,
            createBy: '小小'
        }


        if (!data.dname) {
            return alert('请输入字典名称');
        }
        if (!data.dtype) {
            return alert('请输入字典类型');
        }
        if (data.dstate == undefined) {
            return alert('请选择字典状态');
        }
        const res = await axios.post(`http://localhost/dict/add`, data);
        if (res.data.code == 200) {
            alert('保存成功');
            $('#editModal').modal('hide');
            fetchDictData();

        }

    }

</script>
</body>

</html>